﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

namespace OrderApp {

    /**
     * The service class to manage orders
     * */
    public class OrderService {

        public OrderService() {
            
        }


        public List<Order> GetAllOrders() {
            using(var db = new OrderContext()) {
                return db.Orders.ToList();
            }
        }


        public Order GetOrder(int id) {
            using(var db = new OrderContext()) {
                return db.Orders.Find(id);
            }
        }

        public void AddOrder(Order order) {
            using (var db = new OrderContext()) {
                db.Orders.Add(order);
                db.SaveChanges();
            }
        }

        public void RemoveOrder(int orderId) {
            using (var db = new OrderContext())
            {
                var order = db.Orders.Find(orderId);
                if (order != null)
                {
                    db.Orders.Remove(order);
                    db.Entry(order).State = System.Data.Entity.EntityState.Deleted;
                    db.SaveChanges();
                }
                else
                {
                    throw new ApplicationException($"删除错误：订单 {orderId} 不存在!");
                }
            }
        }

        public List<Order> QueryOrdersByProductName(string productName) {
            using (var db = new OrderContext())
            {
                return db.Orders
                    .Where(order => order.Details.Any(detail => detail.ProductName == productName))
                    .OrderBy(o => o.TotalPrice)
                    .ToList();
            }
        }

        public List<Order> QueryOrdersByCustomerName(string customerName) {
            using(var db = new OrderContext()) 
            {
                return db.Orders
                .Where(order => order.CustomerName == customerName)
                .OrderBy(o => o.TotalPrice)
                .ToList();
            }
        }

        public void UpdateOrder(Order newOrder) {
            using (var db = new OrderContext())
            {
                var oldOrder = db.Orders.Find(newOrder.OrderId);
                if (oldOrder == null)
                    throw new ApplicationException($"修改错误：订单 {newOrder.OrderId} 不存在!");
                
                db.Entry(oldOrder).CurrentValues.SetValues(newOrder);
                db.Entry(oldOrder).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
            }

        }

        public void Export(String fileName) {
            XmlSerializer xs = new XmlSerializer(typeof(List<Order>));
            using (FileStream fs = new FileStream(fileName, FileMode.Create)) {
                using(var db= new OrderContext()) {
                    List<Order> temp = db.Orders.ToList();
                    xs.Serialize(fs, temp);
                }
            }
        }

        public void Import(string path) {
            XmlSerializer xs = new XmlSerializer(typeof(List<Order>));
            using (FileStream fs = new FileStream(path, FileMode.Open)) {
                List<Order> temp = (List<Order>)xs.Deserialize(fs);
                using (var db = new OrderContext()) {
                    {
                        temp.ForEach(order => {
                            if (!db.Orders.Contains(order))
                            {
                                db.Orders.Add(order);
                            }
                        }
                );
                    }
                    db.SaveChanges();
                } 
            }
        }

        public object QueryByTotalAmount(float amout) {
            using (var db = new OrderContext())
            {
                return db.Orders
                    .Where(order => order.TotalPrice > amout)
                    .OrderBy(o => o.TotalPrice)
                    .ToList();
            }
        }
    }
}
